<?php
session_start();

// 检查用户是否已登录
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

// 处理添加用户
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action'])) {
    if ($_POST['action'] == 'add_user') {
        $newUser = [
            'username' => $_POST['username'],
            'password' => $_POST['password']
        ];
        
        // 检查用户名是否已存在
        $usersData = file_get_contents('user.txt');
        $users = json_decode($usersData, true);
        $userExists = false;
        
        foreach ($users['users'] as $user) {
            if ($user['username'] === $newUser['username']) {
                $userExists = true;
                break;
            }
        }
        
        if (!$userExists) {
            // 严格按照现有格式添加用户
            $users['users'][] = [
                'username' => $newUser['username'],
                'password' => $newUser['password']
            ];
            // 使用JSON_PRETTY_PRINT保持格式一致
            file_put_contents('user.txt', json_encode($users, JSON_PRETTY_PRINT));
            // 清除POST数据并重定向
            $_POST = array();
            header("Location: index.php?success=1");
            exit();
        } else {
            $error = "用户名已存在！";
            header("Location: index.php?error=1");
            exit();
        }
    }
    elseif ($_POST['action'] == 'edit_user') {
        $oldUsername = $_POST['old_username'];
        $newUsername = $_POST['username'];
        $newPassword = $_POST['password'];
        
        $usersData = file_get_contents('user.txt');
        $users = json_decode($usersData, true);
        
        foreach ($users['users'] as &$user) {
            if ($user['username'] === $oldUsername) {
                $user['username'] = $newUsername;
                $user['password'] = $newPassword;
                break;
            }
        }
        
        file_put_contents('user.txt', json_encode($users, JSON_PRETTY_PRINT));
    }
    elseif ($_POST['action'] == 'approve_user') {
        $username = $_POST['username'];
        $password = $_POST['password'];
        
        // 添加到user.txt
        $usersData = file_get_contents('user.txt');
        $users = json_decode($usersData, true);
        $users['users'][] = ['username' => $username, 'password' => $password];
        file_put_contents('user.txt', json_encode($users, JSON_PRETTY_PRINT));
        
        // 从待审批列表中移除
        $pendingData = file_get_contents('pending_users.txt');
        $pendingUsers = json_decode($pendingData, true);
        $pendingUsers['users'] = array_filter($pendingUsers['users'], function($user) use ($username) {
            return $user['username'] !== $username;
        });
        file_put_contents('pending_users.txt', json_encode($pendingUsers, JSON_PRETTY_PRINT));
    }
    elseif ($_POST['action'] == 'reject_user') {
        $username = $_POST['username'];
        
        // 从待审批列表中移除
        $pendingData = file_get_contents('pending_users.txt');
        $pendingUsers = json_decode($pendingData, true);
        $pendingUsers['users'] = array_filter($pendingUsers['users'], function($user) use ($username) {
            return $user['username'] !== $username;
        });
        file_put_contents('pending_users.txt', json_encode($pendingUsers, JSON_PRETTY_PRINT));
    }
    elseif ($_POST['action'] == 'delete_user') {
        $username = $_POST['username'];
        $usersData = file_get_contents('user.txt');
        $users = json_decode($usersData, true);
        $users['users'] = array_filter($users['users'], function($user) use ($username) {
            return $user['username'] !== $username;
        });
        file_put_contents('user.txt', json_encode($users, JSON_PRETTY_PRINT));
    }
}

// 读取用户数据
$usersData = file_get_contents('user.txt');
$users = json_decode($usersData, true);

// 读取待审批用户数据
$pendingData = file_exists('pending_users.txt') ? file_get_contents('pending_users.txt') : '{"users":[]}';
$pendingUsers = json_decode($pendingData, true);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>原创软件用户管理 - 用户管理</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f4f4f4;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .section {
            background: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .api-link {
            color: #007bff;
            text-decoration: none;
            font-size: 14px;
            margin-left: 20px;
        }
        .api-link:hover {
            text-decoration: underline;
        }
        .logout-btn {
            padding: 8px 15px;
            background-color: #dc3545;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            min-width: 100px;
        }
        .logout-btn:hover {
            background-color: #c82333;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f8f9fa;
        }
        .btn {
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            font-size: 14px;
            min-width: 80px;
            text-align: center;
            display: inline-block;
            margin-right: 5px;
        }
        .btn-edit {
            background-color: #ffc107;
            color: black;
        }
        .btn-delete {
            background-color: #dc3545 !important;
            color: white !important;
            border: none !important;
            padding: 8px 15px !important;
            border-radius: 4px !important;
            cursor: pointer !important;
            margin-right: 5px !important;
            min-width: 80px !important;
            text-align: center !important;
            display: inline-block !important;
        }
        .btn-approve {
            background-color: #28a745;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 5px;
            min-width: 80px;
            text-align: center;
            display: inline-block;
        }
        .btn-reject {
            background-color: #dc3545 !important;
            color: white !important;
            border: none !important;
            padding: 8px 15px !important;
            border-radius: 4px !important;
            cursor: pointer !important;
            margin-right: 5px !important;
            min-width: 80px !important;
            text-align: center !important;
            display: inline-block !important;
        }
        .add-user-btn, .logout-btn {
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            font-size: 14px;
            min-width: 80px;
            text-align: center;
            display: inline-block;
            margin-right: 5px;
        }
        .add-user-btn {
            background-color: #28a745;
            color: white;
        }
        .logout-btn {
            background-color: #dc3545;
            color: white;
        }
        .btn-save, .btn-cancel {
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            font-size: 14px;
            min-width: 80px;
            text-align: center;
            display: inline-block;
            margin-right: 5px;
        }
        .btn-save {
            background-color: #28a745;
            color: white;
        }
        .btn-cancel {
            background-color: #6c757d;
            color: white;
        }
        .btn:hover, .add-user-btn:hover, .logout-btn:hover, .btn-save:hover, .btn-cancel:hover {
            opacity: 0.9;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
        }
        .form-group input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button[type="submit"] {
            background-color: #007bff;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button[type="submit"]:hover {
            background-color: #0056b3;
        }
        /* 编辑对话框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            z-index: 1000;
        }
        .modal-content {
            background-color: white;
            margin: 15% auto;
            padding: 20px;
            border-radius: 5px;
            width: 400px;
            box-shadow: 0 0 10px rgba(0,0,0,0.3);
        }
        .close {
            float: right;
            cursor: pointer;
            font-size: 24px;
        }
        .add-user-btn:hover {
            background-color: #218838;
        }
        .modal-footer {
            margin-top: 20px;
            text-align: right;
        }
        .modal-footer button {
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
        }
        .error-message, .success-message {
            margin-top: 10px;
            text-align: center;
            padding: 10px;
            border-radius: 4px;
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 1000;
            animation: fadeOut 3s forwards;
        }
        .error-message {
            color: #dc3545;
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
        }
        .success-message {
            color: #28a745;
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
        }
        @keyframes fadeOut {
            0% { opacity: 1; }
            70% { opacity: 1; }
            100% { opacity: 0; }
        }
    </style>
    <script>
        // 防止表单重复提交
        if (window.history.replaceState) {
            window.history.replaceState(null, null, window.location.href);
        }
        
        // 清除表单数据
        function clearForm() {
            document.getElementById('new_username').value = '';
            document.getElementById('new_password').value = '';
        }
        
        // 修改打开对话框的函数
        function openAddUserModal() {
            document.getElementById('addUserModal').style.display = 'block';
            clearForm();
        }

        // 页面加载时检查消息
        window.onload = function() {
            const urlParams = new URLSearchParams(window.location.search);
            
            // 检查错误消息
            if (urlParams.has('error')) {
                const errorDiv = document.createElement('div');
                errorDiv.className = 'error-message';
                errorDiv.textContent = '用户名已存在！';
                document.body.appendChild(errorDiv);
                
                // 3秒后移除消息并清除URL参数
                setTimeout(() => {
                    errorDiv.remove();
                    window.history.replaceState({}, document.title, window.location.pathname);
                }, 3000);
            }
            
            // 检查成功消息
            if (urlParams.has('success')) {
                const successDiv = document.createElement('div');
                successDiv.className = 'success-message';
                successDiv.textContent = '用户添加成功！';
                document.body.appendChild(successDiv);
                
                // 3秒后移除消息并清除URL参数
                setTimeout(() => {
                    successDiv.remove();
                    window.history.replaceState({}, document.title, window.location.pathname);
                }, 3000);
            }
        }
    </script>
</head>
<body>
    <div class="container">
        <div class="header">
            <div style="display: flex; align-items: center;">
                <h1>用户管理系统</h1>
                <a href="https://blog.lahong.top:8888/!/user.txt" class="api-link" target="_blank">API接口</a>
            </div>
            <div>
                <button class="add-user-btn" onclick="openAddUserModal()">添加用户</button>
                <a href="logout.php" class="logout-btn">退出登录</a>
            </div>
        </div>

        <?php if (isset($error)): ?>
            <div class="error-message">
                <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>

        <!-- 用户列表区域 -->
        <div class="section">
            <h2>用户列表</h2>
            <table>
                <thead>
                    <tr>
                        <th>用户名</th>
                        <th>密码</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users['users'] as $user): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($user['username']); ?></td>
                        <td><?php echo htmlspecialchars($user['password']); ?></td>
                        <td>
                            <button onclick="openEditModal('<?php echo htmlspecialchars($user['username']); ?>', '<?php echo htmlspecialchars($user['password']); ?>')" class="btn btn-edit">编辑</button>
                            <form action="" method="post" style="display: inline;">
                                <input type="hidden" name="action" value="delete_user">
                                <input type="hidden" name="username" value="<?php echo htmlspecialchars($user['username']); ?>">
                                <button type="submit" class="btn btn-delete">删除</button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- 待审批用户区域 -->
        <div class="section">
            <h2>待审批用户</h2>
            <table>
                <thead>
                    <tr>
                        <th>用户名</th>
                        <th>密码</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($pendingUsers['users'] as $user): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($user['username']); ?></td>
                        <td><?php echo htmlspecialchars($user['password']); ?></td>
                        <td>
                            <form action="" method="post" style="display: inline;">
                                <input type="hidden" name="action" value="approve_user">
                                <input type="hidden" name="username" value="<?php echo htmlspecialchars($user['username']); ?>">
                                <input type="hidden" name="password" value="<?php echo htmlspecialchars($user['password']); ?>">
                                <button type="submit" class="btn btn-approve">通过</button>
                            </form>
                            <form action="" method="post" style="display: inline;">
                                <input type="hidden" name="action" value="reject_user">
                                <input type="hidden" name="username" value="<?php echo htmlspecialchars($user['username']); ?>">
                                <button type="submit" class="btn btn-reject">拒绝</button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 添加用户对话框 -->
    <div id="addUserModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeAddUserModal()">&times;</span>
            <h2>添加用户</h2>
            <form action="" method="post" id="addUserForm">
                <input type="hidden" name="action" value="add_user">
                <div class="form-group">
                    <label for="new_username">用户名：</label>
                    <input type="text" id="new_username" name="username" required>
                </div>
                <div class="form-group">
                    <label for="new_password">密码：</label>
                    <input type="password" id="new_password" name="password" required>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-cancel" onclick="closeAddUserModal()">取消</button>
                    <button type="submit" class="btn-save">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 编辑用户对话框 -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeEditModal()">&times;</span>
            <h2>编辑用户</h2>
            <form action="" method="post">
                <input type="hidden" name="action" value="edit_user">
                <input type="hidden" name="old_username" id="old_username">
                <div class="form-group">
                    <label for="edit_username">用户名：</label>
                    <input type="text" id="edit_username" name="username" required>
                </div>
                <div class="form-group">
                    <label for="edit_password">密码：</label>
                    <input type="password" id="edit_password" name="password" required>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-cancel" onclick="closeEditModal()">取消</button>
                    <button type="submit" class="btn-save">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function openAddUserModal() {
            document.getElementById('addUserModal').style.display = 'block';
            document.getElementById('new_username').value = '';
            document.getElementById('new_password').value = '';
        }

        function closeAddUserModal() {
            document.getElementById('addUserModal').style.display = 'none';
        }

        function openEditModal(username, password) {
            document.getElementById('editModal').style.display = 'block';
            document.getElementById('old_username').value = username;
            document.getElementById('edit_username').value = username;
            document.getElementById('edit_password').value = password;
        }

        function closeEditModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            if (event.target == document.getElementById('addUserModal')) {
                closeAddUserModal();
            }
            if (event.target == document.getElementById('editModal')) {
                closeEditModal();
            }
        }
    </script>
</body>
</html> 